<template>
  <div>
    <h1>用户名密码</h1>
    <el-form ref="dataForm" :rules="formRules" :model="entity">
      <el-form-item prop="username">
        <j-input-wrapper>
          <el-input
            ref="usernameInput"
            v-model="entity.username"
            @keyup.enter="$refs.passwordInput.focus()"
            placeholder="用户名"
            :readonly="!finished"
          />
        </j-input-wrapper>
      </el-form-item>

      <el-form-item prop="password">
        <j-input-wrapper>
          <el-input
            ref="passwordInput"
            v-model="entity.password"
            type="password"
            @keyup.enter="showCaptchaHandler"
            placeholder="密码"
            :readonly="!finished"
          />
        </j-input-wrapper>
      </el-form-item>

      <br />
      <el-button
        type="primary"
        :loading="loginLoading"
        @click="showCaptchaHandler"
        >登录</el-button
      >
    </el-form>
  </div>
</template>
<script>
import { login } from '@/api/login'

export default {
  name: 'Password',
  emits: ['captcha', 'login-success'],
  data() {
    return {
      entity: {
        username: '',
        password: '',
        userType: 'ADMIN',
      },
      formRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      },
      loginLoading: false,
      finished: false,
    }
  },
  mounted() {
    setTimeout(() => {
      this.finished = true
    }, 300)
  },
  methods: {
    showCaptchaHandler() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.$emit('captcha', this.verifySuccessHandler)
        }
      })
    },
    verifySuccessHandler(captchaVerification) {
      this.loginLoading = true

      let data = Object.assign(this.entity, captchaVerification)
      login(data)
        .then(() => {
          this.$message.success('登录成功')
          this.$emit('login-success')
        })
        .finally(() => {
          this.loginLoading = false
        })
    },
  },
}
</script>
